import java.awt.Graphics;
import java.awt.image.ImageObserver;


public class Invader extends GameObject{

	private Boolean alive = true;
	private Boolean garbage = false;
	private Boolean canFire = false;
	private int pointValue;
	
	static int slowLaserSpeed = 8/InvaderSaver.GAMESPEED_MODIFIER;
	static int fastLaserSpeed = 12/InvaderSaver.GAMESPEED_MODIFIER;
	
	private static final int DEATH_ANIM_COOLDOWN = 1*InvaderSaver.GAMESPEED_MODIFIER;
	private static int deathAnimWait;
	
	private Invader nextAbove = null;
	
	public Invader(int x, int y, Sprite sprite, int points, Boolean firable, Invader nextAbove){
		super(x, y, sprite);
		pointValue = points;
		canFire = firable;
		this.nextAbove = nextAbove;
		deathAnimWait = 0;
	}
	
	/**
	 * The aliens will all move in synchronicity, at intervals specified by the Wave class
	 * 
	 * @param advance - determines if the aliens advance downwards this time or not.
	 */
	public void update(Boolean advance, int hmovement, int numLeft){
		if(alive){
			if(advance)
			{
				y_position += sprite.image_height/2;
			}
			else
			{
				x_position += hmovement; // alters the horizontal position. will often be zero.
				if(hmovement != 0) image_index++; // change the sprite each time they move.
				
				// check of the next move would put the Invader outside the movement bounds. If so, flag Wave.atScreenEdge
				if((x_position > InvaderSaver.getGameWidth() - sprite.image_width && hmovement > 0) || (x_position < sprite.image_width && hmovement < 0))
				{
					Wave.atScreenEdge = true;
				}
			}
		}
		else{
			if(deathAnimWait >= DEATH_ANIM_COOLDOWN){
				image_index++;
				deathAnimWait = 0;
			}
			deathAnimWait++;
			if(image_index >= sprite.getTotalFrames()){
				garbage = true;
			}
		}
		
		// With some probability, fire
		if(canFire && Math.random() < 1.0/(numLeft*3)/InvaderSaver.GAMESPEED_MODIFIER){ //TODO: fast shots too?
			ProjectileControl.addProjectile(x_position, y_position, SpriteLib.INVADER_LASER, slowLaserSpeed);
		}
	}
	
	public void load(){
		canFire = true;
	}
	
	public void die(){
		alive = false;
		sprite = SpriteLib.INVADER_DEATH;
		image_index = 0;
		HUD.modifyScore(pointValue);
		if(nextAbove != null){
			nextAbove.load();
		}
	}
	
	public Boolean garbageCollectMe(){
		return garbage;
	}
	
	public Boolean isAlive(){
		return alive;
	}
	
//	/**
//	 * draw the image using the provided Graphics object.
//	 * @param g
//	 * @param io
//	 */
//	public void draw(Graphics g, ImageObserver io){
//		g.drawImage(sprite.getFrame(image_index), x_position, y_position, io);
//	}
}
